var app = getApp();
var offset = 0;

function requestQuestion(that,d3){
  var initData = getCurrentPages()[0].data.subject
  var t2 = 1 ;
  var o = initData.question[d3].options;
  var l = o.length;
  for(var s = 0; s < l;s ++){
    if (o[s].type != 1) {
      t2 = 2;
      break 
    }
  };

  if (initData.question[d3].type == 3) {
    wx.getStorage({
      key: 'isSort',
      success: function (res) {
      },
      fail: function () {
        wx.showModal({
          title: '提示',
          content: '排序题目,拖动问题答案,可排列想要的顺序',
          confirmText: '好的',
          cancelText: '不再提示',
          success: function (res) {
            if (res.confirm) {
            } else if (res.cancel) {
              wx.setStorage({
                key: "isSort",
                data: true
              })
            }
          }
        })
      }
    })

  }

  var liD = initData.question[d3];
  var lidType = { t1: initData.question[d3].type, t2: t2 };
  that.setData({
    question_num: d3,
    lisData: liD,
    lidType: lidType,
  });

  var ddd = that.data.lisData;
  ddd.select_option = 0;
  var lk = 1;

  for (var tt = 0; tt < ddd.options.length; tt++) {
    ddd.options[tt].id = lk;
    lk++
  };

  that.setData({
    lisData: ddd
  });

  that.setData({
    multiple: lidType.t1 == 2 ? multiple() : '',
  });

  function multiple() {
    var lll = liD.options.length;
    var arry = [];
    if (ddd.select_option != 0) {
      for (var rr = 0; rr < lll; rr++) {
        if (ddd.select_option.indexOf(ddd.options[rr].id == -1)) {
          arry[rr] = false
        } else {
          arry[rr] = true
        }
      }
    } else {
      for (var rr = 0; rr < lll; rr++) {
        arry[rr] = false
      }
    }
    return arry
  };

  var query = wx.createSelectorQuery();
  for (var ttt = 0; ttt < l; ttt++) {
    query.select('#textL'+ttt).boundingClientRect()
    query.exec(function (res) {
        that.setData({
          textL:res
        });
    });
  };

  wx.hideLoading();
};

function insertCopy(arr, index, item) {
  return arr.splice(index, 0, item);
};

function removeCopy(arr, dx) {
  if (isNaN(dx) || dx > arr.length) { return false; }
  for (var i = 0, n = 0; i < arr.length; i++) {
    if (arr[i] != arr[dx]) {
      arr[n++] = arr[i]
    }
  }
  return arr.length -= 1
}


// pages/reply/reply.js
Page({
  data: {
    showHomePage:true,
    drapIndex:undefined,
    drapData:{
      listHeight:0,
      content:'',
      show:'none'
    },
    next: false,
    isFold: true,
    canSort:false,
    animation: {},
    lisData: '',
    moreTitle: '',
    next_num:0,
    pre_num: 0,
    question_num:0,
    delay:false,
    multiple:[],
    region: ['广东省', '广州市', '海珠区'],
    customItem: '全部'
  },

  onLoad: function (options) {

    var that = this;
    this.setData({
      question_id: parseInt(options.id),
    });

    console.log(getCurrentPages()[0])

    that.setData({
      titleLength: that.strLen(getCurrentPages()[0].data.subject.title),
      describeLength: that.strLen(getCurrentPages()[0].data.subject.describe),
      cover:getCurrentPages()[0].data.subject.banner,
      title:getCurrentPages()[0].data.subject.title,
      describe: getCurrentPages()[0].data.subject.describe,
      question_count: getCurrentPages()[0].data.subject.question.length,
      oldType: getCurrentPages()[0].data.oldType,
    });

  },

  strLen: function (str) {
    var len = 0;
    for (var i = 0; i < str.length; i++) {
      var c = str.charCodeAt(i);
      //单字节加1 
      if ((c >= 0x0001 && c <= 0x007e) || (0xff60 <= c && c <= 0xff9f)) {
        len++;
      }
      else {
        len += 2;
      }
    }
    return len;
  },

  radioChange: function (e) {
    var that = this;
    var iD = e.detail.value;
    var d = that.data.lisData.options;
    var dLendth = that.data.lisData.options.length;
    
    //如果是逻辑题   设置下一题
    if (that.data.lidType.t1 == 5){
      for (var uu = 0; uu < dLendth; uu++){
        if (iD == d[uu].id){
           that.setData({
             next_num: d[uu].next_question == '0' ? Number(that.data.question_num) + 1 : d[uu].next_question -1
           })
        };
      };
    };

    that.setData({
      ['lisData.options']:d,
      ['lisData.select_option']: iD,
    });
  },

  checkboxChange: function (e) {
    var that = this;
    var iD = e.detail.value;
    var d = that.data.lisData.options;
    var dLendth = that.data.lisData.options.length;
    
    var multiple = that.data.multiple;

    that.setData({
      ['lisData.options']: d,
      ['lisData.select_option']: iD,
    });

    if (that.data.lisData.select_option != 0) {
      var ld = that.data.lisData;
      for (var rr = 0; rr < dLendth; rr++) {
        if (ld.select_option.indexOf(ld.options[rr].id.toString()) == '-1') {
          multiple[rr] = false
        } else {
          multiple[rr] = true
        }
      }
    } else {
      for (var rr = 0; rr < dLendth; rr++) {
          multiple[rr] = false
      }
    };
    that.setData({
      multiple: multiple
    });
  },
  
  moreTtile:function(){
    var that = this;
    that.setData({
      isFold:false
    });
    var query = wx.createSelectorQuery();
    query.select('#moreContent').boundingClientRect();
    query.exec(function (res) {
      that.animation.bottom(- res[0].height).step({ duration: 300 });
      that.setData({
        animation: that.animation.export(),
      });
    })
  },

  defaultTtile: function () {
    var that = this;
    that.setData({
      isFold: true
    });
    that.animation.bottom('0rpx').step({ duration: 300 });
    that.setData({
      animation: that.animation.export(),
    });
  },

  nex:function(e){
    if (e.currentTarget.dataset.use) {
      return;
    };
    var that = this;
    var isFull = false;
    var question_id = '';
    var da = that.data.lisData;
    var le = that.data.lisData.options.length;
    switch (that.data.lidType.t1){
      case 1:
        if (da.select_option != '0' && da.select_option[0] != undefined) {
                isFull = true;
              };
              if (isFull) {
                wx.showLoading({
                  title: '下一题...',
                });
        
                if (that.data.question_num+1 == that.data.question_count) {
                  var qus = getCurrentPages()[0].data.subject.question;
                  for (var pp = 0; pp < qus.length; pp++) {
                    qus[pp].type = that.data.oldType[pp]
                  };
                  wx.navigateBack({
                    delta: 1
                  })
                return
              }
              
              that.setData({
                next_num: Number(that.data.question_num) + 1,
                pre_num: Number(that.data.question_num)
              });

              requestQuestion(that,that.data.next_num);
                  
              } else {
                wx.showToast({
                  title: '未选择选项!',
                  icon: 'none',
                  duration: 2000,
                })
              }
         break;
      
      case 2:
        if (da.select_option != '0' && da.select_option[0] != undefined) {
          isFull = true;
        };
        if (isFull) {
          if (da.select_num !=0 && da.select_num != da.select_option.length) {
            wx.showToast({
              title: '必选' + da.select_num + '题',
              icon: 'none',
              duration: 2000,
            });
            break
          }
          wx.showLoading({
            title: '下一题...',
          });
      
          if (that.data.question_num + 1 == that.data.question_count) {
            var qus = getCurrentPages()[0].data.subject.question;
            for (var pp = 0; pp < qus.length; pp++) {
              qus[pp].type = that.data.oldType[pp]
            };
            wx.navigateBack({
              delta: 1
            })
            return
          }
      
        that.setData({
          next_num: Number(that.data.question_num) + 1,
          pre_num: Number(that.data.question_num)
        })
        requestQuestion(that, that.data.next_num);
            
        } else {
          wx.showToast({
            title: '未选择选项!',
            icon: 'none',
            duration: 2000,
          })
        }
        break;
      
 
 
      case 3:
        if (da.select_option != '0' && da.select_option[0] != undefined) {
                isFull = true;
              };
              if (isFull) {
                wx.showLoading({
                  title: '下一题...',
                });

                if (that.data.question_num + 1 == that.data.question_count) {
                  var qus = getCurrentPages()[0].data.subject.question;
                  for (var pp = 0; pp < qus.length; pp++) {
                    qus[pp].type = that.data.oldType[pp]
                  };
                  wx.navigateBack({
                    delta: 1
                  })
                  return
                }

              that.setData({
                next_num: Number(that.data.question_num) + 1,
                pre_num: Number(that.data.question_num)
              })

              requestQuestion(that,that.data.next_num);

              } else {
                wx.showToast({
                  title: '未选择选项!',
                  icon: 'none',
                  duration: 2000,
                })
              }
        break;
      case 4:
              var region = that.data.region[0] + ' ' + that.data.region[1] + ' ' + that.data.region[2]
              wx.showLoading({
                title: '下一题...',
              });
           
              if (that.data.question_num + 1 == that.data.question_count) {
                var qus = getCurrentPages()[0].data.subject.question;
                for (var pp = 0; pp < qus.length; pp++) {
                  qus[pp].type = that.data.oldType[pp]
                };
                wx.navigateBack({
                  delta: 1
                })
                return
              }
              
              that.setData({
                next_num: Number(that.data.question_num) + 1,
                pre_num: Number(that.data.question_num)
              });
              requestQuestion(that,that.data.next_num);
                
        break;
      case 5:
        if (da.select_option != '0' && da.select_option[0] != undefined) {
                isFull = true;
              };
              if (isFull) {
                wx.showLoading({
                  title: '下一题...',
                });
 
              if (that.data.question_num + 1 == that.data.question_count) {
                var qus = getCurrentPages()[0].data.subject.question;
                for (var pp = 0; pp < qus.length; pp++) {
                  qus[pp].type = that.data.oldType[pp]
                };
                wx.navigateBack({
                  delta: 1
                })
                return
              }
            
              that.setData({
                pre_num: Number(that.data.question_num)
              });
              console.log(that.data.next_num);
              requestQuestion(that,that.data.next_num);
              } else {
                wx.showToast({
                  title: '未选择选项!',
                  icon: 'none',
                  duration: 2000,
                })
              }
        break;
      case 6:
        break;
      default:
      // n 与 case 1 ~ case 4 不同时执行的代码
    }
  },

  pre: function (e) {
    var that = this;
    var preview = that.data.pre_num;
    if (preview == -1){
      wx.showToast({
        title: '没有上一题',
        icon: 'none',
        duration: 2000,
      })
      return
    };

    wx.showLoading({
      title: '上一题...',
    });

    that.setData({
      question_num: that.data.question_num - 1 < 0 ? 0 : that.data.question_num - 1,
    });
    requestQuestion(that, that.data.question_num);
  },

  onShow: function () {
    var that = this;
    var query = wx.createSelectorQuery();
    query.select('#titleTxt').boundingClientRect()
    query.exec(function (res) {
      if(res[0].width < 250){
        that.setData({
          isFold: false
        });
      }
    });

    that.animation = wx.createAnimation({
      duration: 1000,
      transformOrigin: "100% 0",
      timingFunction: "ease",
    });

    that.setData({
      animation: that.animation.export(),
    });

  },
  
  previewImage:function(t){
    var url = t.currentTarget.dataset.url
    wx.previewImage({
      current: url, // 当前显示图片的http链接
      urls: [url] // 需要预览的图片http链接列表
    })
  },

  bindRegionChange: function (e) {
    this.setData({
      region: e.detail.value
    })
  },

  sortStart:function(e){
    var that = this;
    offset = e.changedTouches[0].pageY;
  },

  sortMove: function (e) {
    var that = this;
    var index = e.currentTarget.dataset.index;
    var xc = e.changedTouches[0].pageY - offset;

    if (parseInt(xc / 60) == 0) {
      return
    }
    that.setData({
      drapIndex: index + parseInt(xc / 60)
    });
  },

  sortEnd: function (e) {

    var that = this;
    var xc = e.changedTouches[0].pageY - offset;
    var index = e.currentTarget.dataset.index;
    var dArr = that.data.lisData.options;
    var textL = that.data.textL;
    var select_option = [];
    
    that.setData({
      drapIndex: 'undefined',
    });

    if (parseInt(xc / 60) == 0) {
      that.setData({
        ['lisData.options']: dArr,
        textL:textL
      });
      return
    };
    
    var indexData = dArr[index];
    var indexTextL = textL[index];

    removeCopy(dArr, index)
    removeCopy(textL, index)
    insertCopy(dArr, index + parseInt(xc / 60), indexData)
    insertCopy(textL, index + parseInt(xc / 60), indexTextL)
    
    for(var ee = 0; ee < dArr.length; ee++){
      select_option[ee] = dArr[ee].id;
    }

    that.setData({
      ['lisData.options']: dArr,
      ['lisData.select_option']: select_option.toString(),
      textL: textL
    });
  },

  sortStart2:function(e){
    var that = this;
    offset = e.changedTouches[0].pageX;
  },

  sortMove2: function (e) {
    var that = this;
    var index = e.currentTarget.dataset.index;
    var xc = e.changedTouches[0].pageX - offset;
    if (parseInt(xc / 88) == 0 || index + parseInt(xc / 88) == -1 || index + parseInt(xc / 88) > that.data.lisData.options.length - 1) {
      return
    }
    that.setData({
      drapIndex: index + parseInt(xc / 88)
    });
  },
  
  sortEnd2: function (e) {

    var that = this;
    var xc = e.changedTouches[0].pageX - offset;
    var index = e.currentTarget.dataset.index;
    var dArr = that.data.lisData.options;
    var select_option = [];
    
    if (parseInt(xc / 88) == 0 || index + parseInt(xc / 88) == -1 || index + parseInt(xc / 88) > dArr.length - 1) {
      that.setData({
        ['lisData.options']: dArr,
      });
      return
    }

    that.setData({
      drapIndex: 'undefined',
    });

    if (parseInt(xc / 88) == 0) {
      that.setData({
        ['lisData.options']: dArr,
      });
      return
    };

    var indexData = dArr[index];
    removeCopy(dArr, index)
    insertCopy(dArr, index + parseInt(xc / 88), indexData)

    for (var ee = 0; ee < dArr.length; ee++) {
      select_option[ee] = dArr[ee].id;
    }

    that.setData({
      ['lisData.options']: dArr,
      ['lisData.select_option']: select_option.toString(),
    });
  },
  
  goAnser:function(){
    var that = this;
    var qus = getCurrentPages()[0].data.subject.question;
    for (var pp = 0; pp < qus.length; pp++) {
      qus[pp].type = that.data.oldType[pp]
    };

    wx.navigateBack({
      delta: 1
    })
  },

  nvgto:function(){
    this.setData({
      showHomePage:false
    });

    requestQuestion(this, this.data.question_num);

  },

  onHide:function(){
    var that = this;
    var qus = getCurrentPages()[0].data.subject.question;
    for (var pp = 0; pp < qus.length; pp++) {
      qus[pp].type = that.data.oldType[pp]
    };
    console.log(qus)
  },

  more: function (e) {
    this.setData({
      showModalData: e.target.dataset.showmodaldata,
      showModal: true
    });
  },
  hideModal: function () {
    this.setData({
      showModalData: '',
      showModal: false
    });
  },

  seeAll:function(e){
    wx.showModal({
      title: '查看',
      content: e.currentTarget.dataset.content,
      showCancel: false,
      confirmText: '确定'
    })

  }
})